
cc.Class({
    extends: cc.Component,

    properties: {
        audio: {
            type: cc.AudioClip,
            default: null,
        },
        // process
        label: {
            type: cc.Label,
            default: null,
        },
        // volume
        volSlider: {
            type: cc.Slider,
            default: null,
        }

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.maxNum = cc.audioEngine.getMaxAudioInstance();
        this.audioPool = [];
        this.volSlider.progress = 0.5;
    },

    start () {

    },

    update (dt) {
        if (!this.label) return;

        for (let i=0; i<this.audioPool.length; ++i) {
            const id = this.audioPool[i];
            const state = cc.audioEngine.getState(id);
            if (state < 0) {
                this.audioPool.splice(i, 1);
                i--;
            }
        }
        this.label.string = 'Instance: ' + this.audioPool.length + ' / ' + this.maxNum;
    },
    play() {
        if (!this.audio) return;
        const id = cc.audioEngine.play(this.audio, false, this.volSlider.progress);
        this.audioPool.push(id);
        cc.log(`current audio pool = ${this.audioPool.length}`);
    },
    stopAll() {
        if(!this.audio) return;
        cc.audioEngine.stopAll();
    },
    pauseAll() {
        if(!this.audio) return;
        cc.audioEngine.pauseAll();
    },
    resumeAll() {
        if(!this.audio) return;
        cc.audioEngine.resumeAll();
    },
    // change volume
    changeVol(slider) {
        for (let i=0; i<this.audioPool.length;++i) {
            if(this.audioPool[i] < 0) {
                // invalid audio
                continue
            }
            cc.audioEngine.setVolume(this.audioPool[i], slider.progress);
        }
    },
});
